<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏房间 - 网络五子棋</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            backdrop-filter: blur(10px);
        }
        
        header {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 20px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo h1 {
            font-size: 2rem;
        }
        
        .room-info {
            text-align: center;
        }
        
        .room-id {
            font-size: 1.2rem;
            margin-bottom: 5px;
        }
        
        .game-status {
            font-size: 1rem;
            opacity: 0.9;
        }
        
        .user-info {
            text-align: right;
        }
        
        .main-content {
            display: flex;
            min-height: 600px;
        }
        
        .chess-board-container {
            flex: 1;
            padding: 30px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: #f8f9fa;
        }
        
        .players-info {
            display: flex;
            justify-content: space-between;
            width: 100%;
            max-width: 600px;
            margin-bottom: 30px;
        }
        
        .player {
            text-align: center;
            padding: 15px 25px;
            border-radius: 15px;
            background: white;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            min-width: 180px;
        }
        
        .player.white {
            border: 3px solid #764ba2;
        }
        
        .player.black {
            border: 3px solid #333;
        }
        
        .player-name {
            font-size: 1.2rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .player-role {
            font-size: 1rem;
            margin-bottom: 10px;
        }
        
        .player.white .player-role {
            color: #764ba2;
        }
        
        .player.black .player-role {
            color: #333;
        }
        
        .player-turn {
            font-size: 0.9rem;
            color: #ff6b6b;
            font-weight: bold;
            height: 20px;
        }
        
        .chess-board {
            width: 600px;
            height: 600px;
            background: #e9c46a;
            position: relative;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            border: 2px solid #8b5a2b;
        }
        
        .grid-line {
            position: absolute;
            background: #000;
        }
        
        .horizontal {
            width: 100%;
            height: 2px;
            left: 0;
            transform: translateY(-1px);
        }
        
        .vertical {
            width: 2px;
            height: 100%;
            top: 0;
            transform: translateX(-1px);
        }
        
        .chess-piece {
            position: absolute;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            transform: translate(-50%, -50%);
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.3);
            z-index: 10;
        }
        
        .piece-white {
            background: white;
            border: 1px solid #ccc;
        }
        
        .piece-black {
            background: black;
            border: 1px solid #333;
        }
        
        .chat-container {
            width: 400px;
            display: flex;
            flex-direction: column;
            background: white;
        }
        
        .chat-header {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 15px 20px;
            font-size: 1.2rem;
            text-align: center;
        }
        
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            max-height: 400px;
            border-bottom: 1px solid #e1e1e1;
        }
        
        .message {
            margin-bottom: 15px;
            padding: 10px 15px;
            border-radius: 10px;
            max-width: 80%;
            word-wrap: break-word;
        }
        
        .message.own {
            background: #e3f2fd;
            margin-left: auto;
            border-bottom-right-radius: 0;
        }
        
        .message.other {
            background: #f5f5f5;
            margin-right: auto;
            border-bottom-left-radius: 0;
        }
        
        .message-system {
            background: #fff3cd;
            text-align: center;
            max-width: 100%;
            font-size: 0.9rem;
            color: #856404;
        }
        
        .message-sender {
            font-weight: bold;
            margin-bottom: 5px;
            font-size: 0.9rem;
        }
        
        .message-content {
            font-size: 1rem;
        }
        
        .chat-input-container {
            padding: 20px;
            display: flex;
        }
        
        .chat-input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #e1e1e1;
            border-radius: 8px;
            font-size: 1rem;
            margin-right: 10px;
        }
        
        .chat-send {
            background: #667eea;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.3s ease;
        }
        
        .chat-send:hover {
            background: #5a6fd8;
        }
        
        .game-controls {
            padding: 20px;
            text-align: center;
            border-top: 1px solid #e1e1e1;
        }
        
        .control-btn {
            background: #6c757d;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.3s ease;
            margin: 0 10px;
            font-size: 1rem;
        }
        
        .control-btn:hover {
            background: #5a6268;
        }
        
        .control-btn.exit {
            background: #dc3545;
        }
        
        .control-btn.exit:hover {
            background: #c82333;
        }
        
        .message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
            display: none;
        }
        
        .message.error {
            background: #ffe6e6;
            color: #d63031;
            border: 1px solid #ff7675;
        }
        
        .message.success {
            background: #e6f7e6;
            color: #27ae60;
            border: 1px solid #2ecc71;
        }
        
        .winner-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 100;
            display: none;
        }
        
        .winner-content {
            background: white;
            padding: 40px;
            border-radius: 20px;
            text-align: center;
            max-width: 500px;
            width: 90%;
        }
        
        .winner-title {
            font-size: 2.5rem;
            margin-bottom: 20px;
            color: #333;
        }
        
        .winner-name {
            font-size: 2rem;
            color: #ee5a24;
            margin-bottom: 30px;
            font-weight: bold;
        }
        
        .winner-buttons {
            display: flex;
            justify-content: center;
            gap: 20px;
        }
        
        .winner-btn {
            padding: 15px 30px;
            border: none;
            border-radius: 10px;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .winner-btn.again {
            background: #667eea;
            color: white;
        }
        
        .winner-btn.hall {
            background: #6c757d;
            color: white;
        }
        
        .winner-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="logo">
                <h1>⚫ 网络五子棋 ⚪</h1>
            </div>
            <div class="room-info">
                <div class="room-id">房间号: <span id="roomId">--</span></div>
                <div class="game-status" id="gameStatus">等待游戏中...</div>
            </div>
            <div class="user-info">
                <div id="userName">玩家</div>
            </div>
        </header>
        
        <div class="main-content">
            <div class="chess-board-container">
                <div class="players-info">
                    <div class="player white" id="whitePlayer">
                        <div class="player-name" id="whitePlayerName">等待中...</div>
                        <div class="player-role">白棋</div>
                        <div class="player-turn" id="whiteTurn"></div>
                    </div>
                    <div class="player black" id="blackPlayer">
                        <div class="player-name" id="blackPlayerName">等待中...</div>
                        <div class="player-role">黑棋</div>
                        <div class="player-turn" id="blackTurn"></div>
                    </div>
                </div>
                
                <div class="chess-board" id="chessBoard">
                    <!-- 棋盘网格和棋子将通过JavaScript动态生成 -->
                </div>
            </div>
            
            <div class="chat-container">
                <div class="chat-header">游戏聊天</div>
                <div class="chat-messages" id="chatMessages">
                    <div class="message message-system">欢迎来到游戏房间！</div>
                </div>
                <div class="chat-input-container">
                    <input type="text" class="chat-input" id="chatInput" placeholder="输入消息...">
                    <button class="chat-send" onclick="sendMessage()">发送</button>
                </div>
                <div class="game-controls">
                    <button class="control-btn exit" onclick="exitRoom()">退出房间</button>
                </div>
            </div>
        </div>
    </div>
    
    <div id="message" class="message"></div>
    
    <div class="winner-overlay" id="winnerOverlay">
        <div class="winner-content">
            <h2 class="winner-title">游戏结束</h2>
            <div class="winner-name" id="winnerName">玩家名称</div>
            <div class="winner-buttons">
                <button class="winner-btn again" onclick="playAgain()">再玩一局</button>
                <button class="winner-btn hall" onclick="backToHall()">返回大厅</button>
            </div>
        </div>
    </div>

    <script>
        let ws = null;
        let roomId = 0;
        let userId = 0;
        let whiteId = 0;
        let blackId = 0;
        let currentTurn = 0; // 当前回合：0-未开始，1-白棋，2-黑棋
        let myRole = 0; // 0-未知，1-白棋，2-黑棋
        const boardSize = 15;
        const cellSize = 40; // 每个格子的大小
        const boardOffset = 30; // 棋盘边距
        let boardState = Array(boardSize).fill().map(() => Array(boardSize).fill(0)); // 0-空，1-白棋，2-黑棋
        let gameOver = false;

        // 页面加载时建立WebSocket连接
        window.onload = function() {
            connectWebSocket();
            createBoard();
        };

        function connectWebSocket() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/room`;
            
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function() {
                console.log('WebSocket连接已建立');
                showMessage('已连接到游戏房间', 'success');
                setTimeout(() => {
                    document.getElementById('message').style.display = 'none';
                }, 3000);
            };
            
            ws.onmessage = function(event) {
                const data = JSON.parse(event.data);
                handleWebSocketMessage(data);
            };
            
            ws.onclose = function() {
                console.log('WebSocket连接已关闭');
                showMessage('连接已断开，正在重连...', 'error');
                // 尝试重连
                setTimeout(connectWebSocket, 3000);
            };
            
            ws.onerror = function(error) {
                console.error('WebSocket错误:', error);
                showMessage('连接错误，请检查网络', 'error');
            };
        }

        function handleWebSocketMessage(data) {
            if (data.op_type === 'room_ready') {
                if (data.result) {
                    roomId = data.room_id;
                    userId = data.uid;
                    whiteId = data.white_id;
                    blackId = data.black_id;
                    
                    document.getElementById('roomId').textContent = roomId;
                    updatePlayersInfo();
                    
                    // 确定自己的角色
                    if (userId === whiteId) {
                        myRole = 1;
                        document.getElementById('whitePlayerName').textContent = '我 (' + whiteId + ')';
                        document.getElementById('blackPlayerName').textContent = '对手 (' + blackId + ')';
                    } else {
                        myRole = 2;
                        document.getElementById('whitePlayerName').textContent = '对手 (' + whiteId + ')';
                        document.getElementById('blackPlayerName').textContent = '我 (' + blackId + ')';
                    }
                    
                    // 黑棋先手
                    currentTurn = 2;
                    updateTurnIndicator();
                    
                    showMessage('游戏开始！黑棋先行', 'success');
                    setTimeout(() => {
                        document.getElementById('message').style.display = 'none';
                    }, 3000);
                } else {
                    showMessage('进入房间失败: ' + data.reason, 'error');
                    setTimeout(() => {
                        window.location.href = 'hall.html';
                    }, 2000);
                }
            } else if (data.op_type === 'chess') {
                handleChessMessage(data);
            } else if (data.op_type === 'chat') {
                handleChatMessage(data);
            } else if (data.op_type === 'exit') {
                handleExitMessage(data);
            }
        }

        function handleChessMessage(data) {
            if (data.result) {
                const row = data.row;
                const col = data.col;
                const uid = data.uid;
                
                // 更新棋盘状态
                const pieceType = (uid === whiteId) ? 1 : 2;
                boardState[row][col] = pieceType;
                
                // 在棋盘上放置棋子
                placeChessPiece(row, col, pieceType);
                
                // 切换回合
                currentTurn = (currentTurn === 1) ? 2 : 1;
                updateTurnIndicator();
                
                // 检查是否有胜者
                if (data.winner && data.winner > 0) {
                    gameOver = true;
                    const winnerName = (data.winner === whiteId) ? 
                        document.getElementById('whitePlayerName').textContent : 
                        document.getElementById('blackPlayerName').textContent;
                    showWinner(winnerName);
                }
            } else {
                showMessage('落子失败: ' + data.reason, 'error');
            }
        }

        function handleChatMessage(data) {
            if (data.result) {
                addChatMessage(data.uid, data.message, data.uid === userId);
            } else {
                showMessage('发送消息失败: ' + data.reason, 'error');
            }
        }

        function handleExitMessage(data) {
            if (data.result) {
                const winnerName = (data.winner === whiteId) ? 
                    document.getElementById('whitePlayerName').textContent : 
                    document.getElementById('blackPlayerName').textContent;
                showMessage('对手已退出游戏，' + winnerName + '获胜！', 'success');
                gameOver = true;
                showWinner(winnerName);
            }
        }

        function createBoard() {
            const board = document.getElementById('chessBoard');
            board.innerHTML = '';
            
            // 创建网格线
            for (let i = 0; i < boardSize; i++) {
                // 横线
                const horizontalLine = document.createElement('div');
                horizontalLine.className = 'grid-line horizontal';
                horizontalLine.style.top = `${boardOffset + i * cellSize}px`;
                board.appendChild(horizontalLine);
                
                // 竖线
                const verticalLine = document.createElement('div');
                verticalLine.className = 'grid-line vertical';
                verticalLine.style.left = `${boardOffset + i * cellSize}px`;
                board.appendChild(verticalLine);
            }
            
            // 添加棋盘点击事件
            board.addEventListener('click', handleBoardClick);
        }

        function handleBoardClick(event) {
            if (gameOver) return;
            
            // 检查是否轮到当前玩家
            if ((myRole === 1 && currentTurn !== 1) || (myRole === 2 && currentTurn !== 2)) {
                showMessage('还没轮到您下棋！', 'error');
                return;
            }
            
            const rect = event.target.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;
            
            // 计算点击的棋盘位置
            const col = Math.round((x - boardOffset) / cellSize);
            const row = Math.round((y - boardOffset) / cellSize);
            
            // 检查位置是否有效
            if (row >= 0 && row < boardSize && col >= 0 && col < boardSize) {
                // 发送落子消息
                const message = {
                    op_type: 'chess',
                    room_id: roomId,
                    uid: userId,
                    row: row,
                    col: col
                };
                ws.send(JSON.stringify(message));
            }
        }

        function placeChessPiece(row, col, pieceType) {
            const board = document.getElementById('chessBoard');
            const piece = document.createElement('div');
            piece.className = `chess-piece ${pieceType === 1 ? 'piece-white' : 'piece-black'}`;
            piece.style.left = `${boardOffset + col * cellSize}px`;
            piece.style.top = `${boardOffset + row * cellSize}px`;
            board.appendChild(piece);
        }

        function updatePlayersInfo() {
            document.getElementById('whitePlayerName').textContent = `玩家 ${whiteId}`;
            document.getElementById('blackPlayerName').textContent = `玩家 ${blackId}`;
        }

        function updateTurnIndicator() {
            const whiteTurn = document.getElementById('whiteTurn');
            const blackTurn = document.getElementById('blackTurn');
            
            if (currentTurn === 1) {
                whiteTurn.textContent = '当前回合';
                blackTurn.textContent = '';
            } else if (currentTurn === 2) {
                whiteTurn.textContent = '';
                blackTurn.textContent = '当前回合';
            } else {
                whiteTurn.textContent = '';
                blackTurn.textContent = '';
            }
        }

        function sendMessage() {
            const input = document.getElementById('chatInput');
            const message = input.value.trim();
            
            if (message === '') return;
            
            // 发送聊天消息
            const chatMessage = {
                op_type: 'chat',
                room_id: roomId,
                uid: userId,
                message: message
            };
            ws.send(JSON.stringify(chatMessage));
            
            // 清空输入框
            input.value = '';
        }

        function addChatMessage(uid, content, isOwn) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isOwn ? 'own' : 'other'}`;
            
            const sender = document.createElement('div');
            sender.className = 'message-sender';
            sender.textContent = isOwn ? '我' : `玩家 ${uid}`;
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = content;
            
            messageDiv.appendChild(sender);
            messageDiv.appendChild(contentDiv);
            chatMessages.appendChild(messageDiv);
            
            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function exitRoom() {
            if (confirm('确定要退出房间吗？')) {
                // 发送退出消息
                const message = {
                    op_type: 'exit',
                    room_id: roomId,
                    uid: userId
                };
                ws.send(JSON.stringify(message));
                
                // 关闭WebSocket连接
                if (ws) {
                    ws.close();
                }
                
                // 跳转回大厅
                window.location.href = 'hall.html';
            }
        }

        function showWinner(winnerName) {
            document.getElementById('winnerName').textContent = winnerName + ' 获胜！';
            document.getElementById('winnerOverlay').style.display = 'flex';
        }

        function playAgain() {
            // 重新开始游戏
            document.getElementById('winnerOverlay').style.display = 'none';
            resetGame();
        }

        function backToHall() {
            // 关闭WebSocket连接
            if (ws) {
                ws.close();
            }
            // 跳转回大厅
            window.location.href = 'hall.html';
        }

        function resetGame() {
            // 重置游戏状态
            boardState = Array(boardSize).fill().map(() => Array(boardSize).fill(0));
            document.getElementById('chessBoard').innerHTML = '';
            createBoard();
            currentTurn = 2; // 黑棋先手
            updateTurnIndicator();
            gameOver = false;
            
            // 添加系统消息
            addSystemMessage('新游戏开始！黑棋先行');
        }

        function addSystemMessage(content) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message message-system';
            messageDiv.textContent = content;
            chatMessages.appendChild(messageDiv);
            
            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function showMessage(text, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = text;
            messageDiv.className = `message ${type}`;
            messageDiv.style.display = 'block';
            
            if (type === 'success') {
                setTimeout(() => {
                    messageDiv.style.display = 'none';
                }, 3000);
            }
        }
        
        // 允许按Enter键发送消息
        document.getElementById('chatInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>